import es6Ppromise from 'es6-promise';
//@TODO 暂用修改过后的fetch-jsonp当作者不再单纯采用timeout检测再使用
import fetchJsonp from './fetch-jsonp';
import YmtApi from 'YmtApi';

es6Ppromise.polyfill();

export default function request(url, options = {
  //@TODO 这里需要配置timeout,fetchJsonp不支持请求超时，我向作者提了
  //这个问题正在pull request；如果作者接纳则，则不再采用timeout检测
  //是否失败；
  timeout: 0
}, params = {}) {
  return new Promise((resolve, reject) => {
    if (!url) {
      reject(new Error('There is no URL provided for the request.'));
    }

    if (!options) {
      reject(new Error('There are no options provided for the request.'));
    }

    url = YmtApi.utils.addParam(url, params);

    fetchJsonp(url, options).then(response => {
      return response.json();
    }).then(response => {
      if (response.status >= 200 && response.status < 300) {
        return response.errors ? reject(response.errors) : reject(response);
      } else {
        return resolve(response)
      }
    }).catch(error => {
      reject(error);
    });
  });
}